<?php
/**
 * Created by PhpStorm.
 * User: ljw
 * Date: 2016/10/19
 * Time: 11:30
 */
$cnct_flag = false;

error_reporting(E_ALL);   //报告所有错误
set_time_limit(0);        //设置脚本最大执行时间（秒），超时返回致命错误。0 - 没有限制
ob_implicit_flush(true);  //打开绝对刷送

$svc_port = 10000;
$svc_ip   = '192.168.18.30';

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
  echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
  exit;
} else {
  echo "OK.\n";
}

//$stdin = fopen('php://stdin', 'r');

while(true) {
  /*
    $cmd_line = trim(fgets(STDIN));
    switch($cmd_line){
    case "quit":
      echo "Closing socket...\n";
      socket_close($socket);
      echo "Good Bye\n";  exit;
      break;
    default:
      break;
    }
  */

  if (!$cnct_flag) {
    echo "Attempting to connect to '$svc_ip' on port '$svc_port'...\n";
    $result = socket_connect($socket, $svc_ip, $svc_port);

    if ($result === false) {
      echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
      sleep(5);
      continue;
    } else {
      $cnct_flag = true;
      echo "Connected to '$svc_ip' on port '$svc_port'.\n";
    }
  } else {
    $inbuf = socket_read($socket, 2048, PHP_BINARY_READ);
    echo $inbuf;
  }

}

echo "Closing socket...\n";
socket_close($socket);

end:
  echo "Program exit\n";
?>
